<template>
<div id="content-show">
  <div id="content" v-html="contract.content">
    <!-- <el-button @click="save">save</el-button> -->
  </div>
  <div v-if="rightShow" class="right-menu" :style="'position: absolute; top:' + offset.y + 'px;left:' + offset.x + 'px'">
    <el-button type="text" v-if="showDelTr" @click="deleteTr">删除</el-button>
    <el-button type="text" v-if="showDelTr==false" @click="addTr" style="margin: 0">添加</el-button>
    <el-button type="text" v-if="showDelTr==false" @click="dialogVisible = true" style="margin: 0">物料</el-button>
  </div>

  <el-dialog
    title="物料选择"
    :visible.sync="dialogVisible"
    append-to-body
    @close="dialogVisible = false"
    width="900px">
    <table-ext :columns="columns" :searchForm="searchForm" :config="config" ref="tableExt">
      <template slot="table-action">
        <el-button type="primary" size="small"  @click="handleSubmit">选择</el-button>
      </template>
    </table-ext>
  
  </el-dialog>  
</div>
</template>

<script>
  import Vue from 'vue';
  import {Input,DatePicker,Select,Option} from 'element-ui';
  import DateProxy from '@/components/common/contract/DateProxy';
  import TableExt from '@/components/common/table-ext/table-ext';
  import $ from 'jquery';
  export default {
    props: ['value'],
    data(){
      return {
        contract:{
          content: ''
        },
        template:{},
        result:{},
        elMap:{},
        vmMap: {},
        elList:[],
        tableList: [],
        tableMap:{},
        showDelTr:true,
        rightShow: false,
        offset:{
          x: 0,
          y: 0
        },
        tempTr: null,
        dialogVisible: false,
        config:{ // 页面共通配置
          isPage: true, //是否分页
          isNo:true,
          title:'物料',
          currentRow: true,
          prefixCls: 'select',
          tableHeight: '400',
          crudMapping:{
            query:{
              url: this.lib.config.host.masterData + '/mdata/material/getMaterialByFactory',
              data:{'purOrgId':this.purOrgId,"factoryId" : this.factoryId}
              // data:{'purOrgId':this.purOrgId,"factoryId" : this.factoryId,"factoryIds" : this.factoryIds}
            }
          }
        },
        searchForm:[{ // 查询表单配置
          label: '物料编码',
          key: 'materialCode',
          type: 'input'
        },{
          label: '物料名称',
          key: 'materialName',
          type: 'input'
        }],
        columns:[{
          label: '物料编码',
          key: 'materialCode',
          order: true,
          align: 'center',
          width:'150px'
        },{
          label: '物料名称',
          key: 'materialName',
          align: 'center',
          width:'200px'
        },{
          label: '单位编码',
          key: 'purUnitCode',
          align: 'center'
        },{
          label: '单位名称',
          key: 'purUnitName',
          align: 'center',
          width:'100px'
        },{
          label: '库存单位',
          key: 'stockUnitName',
          align:'center',
          width:'100px'
        },{
          label: '集采标识',
          key: 'cpFlag',
          align:'center',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            if(params.row.cpFlag == 1){
              return createElement('div','集采');
            } else  {
              return createElement('div','非集采');
            }
          }
        }]
      };
    },
    components:{
      DateProxy,
      TableExt
    },
    mounted(){
      this.init();
    },
    watch:{
      value(val){
        this.value = val;
        this.init();
      }
    },
    methods:{
      init(){
        if(this.value==''){
          this.contract.content = '';
          this.contract.elList = [];
          return;
        }
        this.axios.post(this.lib.config.host.contract+'/contractmgt/contract/editContent/'+this.value,{}).
        then(res=>{
          let result = res.data;
          let contract = result.resultMap.contract;
          this.contract = contract;
          this.$nextTick(function () {
            this.setElList();
          });
        }).
        catch(e=>{
          this.showMsg('error',e);
        });
      },
      save(){
        let _this = this;
        let otherValMap = {};
        let flag = true;
        for(let key in this.result){
          if(this.result[key]==''){
            _this.showMsg('warning','有选项未填');
            _this.vmMap[key].focus();
            flag = false;
            break;
          }
          if (this.elMap[key].elField && this.elMap[key].elField !== '') {
            _this.contract[this.elMap[key].elField] = this.result[key];
          }else{
            otherValMap[key] = this.result[key];
          }
        }
        if(!flag)return;
        //明细项处理
        let itemList = [];
        this.tableList.forEach(table=>{
          let tb = $('#'+table.elId);
          let $trList = tb.find('tr');
          let item = {};
          $trList.each(function(){
            let $tdList = $(this).find('td');
            if($tdList.length==0){
              return true;
            }
            $tdList.each(function(){
              let input = $(this).find('input')[0];
              item[$(input).attr('name')] = $(input).val();
            });
            itemList.push(item);
          });

        });
        this.contract.itemList = itemList;
        this.contract.otherValMap = otherValMap;
        this.axios.post(this.lib.config.host.contract+'/contractmgt/contract/saveContent',this.contract).
        then(res=>{
          let result = res.data;
          if(result.success){
            this.$emit('editContentSuc');
          }else{
            this.showMsg('error',result.message);
          }
        }).
        catch(e=>{
          this.showMsg('error',e);
        });
      },
      setElList(){
        let _this = this;
        window.onclick=function (e) {
          _this.rightShow = false;
        };
        let elList = this.contract.elList;
        elList.forEach((item)=>{
        this.$set(this.elMap, item.elId, item);
        if (item.elType === 'input') {
          this.mounteInput(item.elId, item);
        } else if (item.elType === 'select') {
          this.mounteSelect(item.elId, item);
        } else if (item.elType === 'selectUrl') {
          this.mounteSelectUrl(item.elId, item);
        } else if (item.elType === 'date') {
          this.mounteDate(item.elId, item);
        } else if (item.elType === 'span') {
            new Vue({
              el: '#' + item.elId,
              data:{
                styleObj:{
                  display: 'inline-block',
                  width: '180px'
                }
              },
              template: '<span :style="styleObj">' + _this.contract[item.elField]+ '</span>'
            })
        } else if (item.elType === 'table') {
            this.tableList.push(item);
            let sourceType = this.contract.sourceType;
            let table = document.getElementById(item.elId);
            table.setAttribute('config',item.elContent);
            this.$set(this.tableMap, item.elId, item);
            let trList = table.querySelectorAll('tr');
            let elConfig = JSON.parse(item.elContent);
            for (let i = 0; i < trList.length; i++) {
              trList[i].setAttribute('tbid',item.elId);
              if(sourceType==0){
              trList[i].oncontextmenu = function (e) {
                e.preventDefault();
                if(i==0){
                _this.showDelTr = false;
                }else{
                  _this.showDelTr = true;
                }
                _this.offset.x = e.clientX;
                _this.offset.y = e.clientY;
                _this.tempTr = this;
                _this.rightShow = true;
              }
              }
              //处理隐藏列
              let tdList = [];
              if(i==0){
                tdList = trList[i].querySelectorAll('th');
              }else{
                tdList = trList[i].querySelectorAll('td');
              }
              tdList.forEach((td,tdIndex)=>{
              if(elConfig[tdIndex].hide == 1){
                td.style.display = 'none';
                td.setAttribute('type','hide');
                td.setAttribute('field',elConfig[tdIndex].field);
              }});              
            }
            //合同初始值的处理
            let itemList = this.contract.itemList;
           
            itemList.forEach(it=>{
               let $tr = $('<tr tbid="'+item.elId+'"></tr>');
               elConfig.forEach(cf=>{
                 let val = it[cf.field]?it[cf.field]:'';
                  if(cf.hide==1){
                    $tr.append($('<td style="display:none;"><input type="hidden" name="'+cf.field+'" value="'+val+'"/></td>'));
                  }else{
                    let readonly = '';
                    if(sourceType==1){
                      readonly = 'readonly';
                    }
                    $tr.append($('<td><input type="text" '+readonly+' name="'+cf.field+'" value="'+val+'"/></td>'));
                  }
               });
               if(sourceType==0){
                    $tr.get(0).oncontextmenu = function (e) {
                    e.preventDefault();
                    _this.showDelTr = true;
                    _this.offset.x = e.clientX;
                    _this.offset.y = e.clientY;
                    _this.tempTr = this;
                    _this.rightShow = true;
                  }
                }
                 $(table).append($tr);
              });
           

          }
      });
      },
      mounteInput(id, item){
        let _this = this;
        let val = '';
          console.debug('otherValMap:'+this.contract.otherValMap);
        if(item.elField!=''){
          val = this.contract[item.elField];
        }else if(this.contract.otherValMap!=null){
          console.debug('otherValMap:'+(this.contract.otherValMap!=null));
          val = this.contract.otherValMap[id];
        }
        this.$set(this.result, item.elId, val);
        let width = this.textWidth(val)+'px';
        let vm = new Vue({
          el: '#' + id,
          parent: this,
          data:{
            value: _this.result[id],
            styleObj: {
              width: width
            }
          },
          template:'<input type="text" v-model="value" :style="styleObj" @input="change"/>',
          methods:{
            change(){
               _this.result[id] = this.value;
               let width =  _this.textWidth(this.value);
               this.styleObj.width = width+'px';
            }
          }
        });
        this.$set(this.vmMap, id, vm);
      },
      mounteSelect(id, item){
        let _this = this;
        let val = '';
        if(item.elField!=''){
          val = this.contract[item.elField];
        }else if(this.contract.otherValMap){
          val = this.contract.otherValMap[id];
        }
        this.$set(this.result, item.elId, val);
        let options = JSON.parse(item.elContent);
        new Vue({
          el: '#'+id,
          parent: this,
          data:{
            value: val,
            options:options
          },
          template:'<el-select v-model="value" @change="change"><el-option v-for="item in options" :key="item.value" :label="item.value" :value="item.value"/></el-select>',
          methods:{
            change(v){
                _this.result[id] = v;
            }
          }
        });
      },
      mounteSelectUrl(id, item) {
        let _this = this;
        let _options = [];
        let val = '';
        let config = JSON.parse(item.elFormat);
        let valueDef = 'item.value'; 
        if(config.text==item.elField){
            valueDef = 'item.text'; 
        }
        let remote = true;
        if(config.once){
            remote= false;
        }
        if(item.elField!=''){
          val = this.contract[item.elField];
        }else if(this.contract.otherValMap){
          val = this.contract.otherValMap[id];
        }
        if(val){
          _options.push({value:val,text:this.contract[config.text]});
        }
        this.$set(this.result, item.elId, val);
        let disabled = (this.contract.sourceType==1 && item.elField=='vendorId')?true:false;        
        this.$set(this.result, item.elId, val);
          new Vue({
            el: '#' + id,
            parent: this,
            data: {
              remote:remote,
              loading: false,
              options: _options,
              disabled: disabled,
              value: val
            },
            mounted(){
              if(!remote){
                this.axios.post(item.elDataRepo,{}).
                then(res=>{
                  this.options=res.data;
                });
              }
            },
            template:'<span><el-select :disabled="disabled" v-model="value" filterable :remote="remote" :loading="loading" :remote-method="query" @change="change">'+
            '<el-option v-for="item in options" :key="item.value" :label="item.text" :value="'+valueDef+'"/></el-select></span>',
            methods: {
              query(param){
                 if (param !== '') {
                    this.loading = true;
                    this.axios.post(item.elDataRepo+'/'+param,{}).
                    then(res=>{
                      var result = res.data;
                      this.options = result;
                      this.loading = false;
                    });
                  } else {
                    this.options = [];
                  }
              },
              change(v){
                _this.result[id] = v;
              }
            }
          });
      },      
      mounteDate(id, item){
        let _this = this;
        let val = '';
        if(item.elField!=''){
          val = this.contract[item.elField];
        }else{
          val = this.contract.otherValMap[id];
        }
        this.$set(this.result, item.elId, val);
        let a = Vue.extend(DateProxy);
        new a({
          el: '#' + id,
          props:['value'],
          parent:this,
          propsData:{
            value: _this.result[id],
            format: item.elFormat
          }
        }).$on('change',(val)=>{
          _this.result[id] = val
        });
      },
      handleSubmit(){ //物料确认
        let data = this.$refs.tableExt.getCurrentRow();
        let tableId = this.tempTr.parentNode.parentNode.id;
        let com = this.tempTr.cloneNode(true);
        let thList = com.querySelectorAll('th');
        thList.forEach(th=>{
          com.removeChild(th);
        });
        let table = document.getElementById(tableId);
        let configStr = table.getAttribute('config');
        let configList = JSON.parse(configStr);
        configList.forEach(config=>{
          let val = data[config.field];
          if(config.field=='unitId'){
            val = data['purUnitId'];
          }else if(config.field=='unitCode'){
            val = data['purUnitCode'];
          }else if(config.field=='unitName'){
            val = data['purUnitName'];
          }
          let hide = config.hide == 1
          let display = hide?'display:none':'';
          let input = hide?'<input type="hidden" name="'+config.field+'"/>':'<input type="text" name="'+config.field+'"/>';
          let td = document.createElement('td');
          if(hide){
            td.style.display = 'none';
            let input = document.createElement('input');
            input.type = 'hidden';
            input.name = config.field;
            input.value =val?val:'';
            td.appendChild(input);
          }else{
            let input = document.createElement('input');
            input.type = 'text';
            input.name = config.field;
            input.value =val?val:'';
            td.appendChild(input);
          }
          com.appendChild(td);
        });
        let _this = this;
        com.oncontextmenu = function (e) {
          e.preventDefault();
          _this.showDelTr = true;
          _this.offset.x = e.clientX;
          _this.offset.y = e.clientY;
          _this.tempTr = this;
          _this.rightShow = true;
        }
        this.tempTr.parentNode.appendChild(com);
        this.dialogVisible = false;
      },
      deleteTr(){
        this.tempTr.parentNode.removeChild(this.tempTr);
      },
      addTr(){
        let _this = this;
        let com = this.tempTr.cloneNode(true);
        let thList = com.querySelectorAll('th');
        thList.forEach(th=>{
          com.removeChild(th);
        });
        let tbId = com.getAttribute('tbid');
        let table = document.getElementById(tbId);
        let configStr = table.getAttribute('config');
        let configList = JSON.parse(configStr);
        configList.forEach(config=>{
          let hide = config.hide == 1
          let display = hide?'display:none':'';
          let input = hide?'<input type="hidden" name="'+config.field+'"/>':'<input type="text" name="'+config.field+'"/>';
          let td = document.createElement('td');
          if(hide){
            td.style.display = 'none';
            let input = document.createElement('input');
            input.type = 'hidden';
            input.name = config.field;
            td.appendChild(input);
          }else{
            let input = document.createElement('input');
            input.type = 'text';
            input.name = config.field;
            td.appendChild(input);
          }
          com.appendChild(td);
        });
        com.oncontextmenu = function (e) {
          e.preventDefault();
          _this.showDelTr = true;
          _this.offset.x = e.clientX;
          _this.offset.y = e.clientY;
          _this.tempTr = this;
          _this.rightShow = true;
        }
        this.tempTr.parentNode.appendChild(com);
      },
      textWidth(val){
        var text = val+"1";
        var sensor = $('<pre>' + text + '</pre>').css({display: 'none'});
        $('body').append(sensor);
        var width = sensor.width();
        sensor.remove();
        if(width < 50) width = 50;
        return width;
      }
    }
  }
</script>

<style>
  #content-show .el-input,.ue-tag {
    width: 180px;
  }

  #content-show span {
    text-indent: 0px;
  }

  /* #content-show p>span:nth-child(1){
    text-indent: 28px;
  } */
  #content-show table {
    border-top: 1px solid #d2dcf8;
    border-right: 1px solid #d2dcf8;
  }

  #content-show table tr th,#content-show td {
    border-bottom: 1px solid #d2dcf8;
    border-left: 1px solid #d2dcf8;
    padding: 4px 6px;
  }

  #content-show .right-menu{
    display: flex;
    flex-direction: column;
    z-index: 99;
    background-color: #fff;
    width: 120px;
    border: 1px solid #d2dcf8;
    padding: 8px;
  }

  #content-show input{
    border-bottom: 1px solid #409EFF;
  }
</style>
